package com.jlz.service;


import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.julewa.db.DB;
import com.julewa.db.Identifier;

//这个类的实现,目前只适用于单机的情况
@Component 
public class IdentifierService implements Identifier{
	private @Autowired DB db;
	//
	private class Generator{
		private String type = null;
		private String suffix = null;
		private long id = 0;
		//
		public Generator(String type){
			this.type = type;
			id = type.indexOf("?");
			if(id > 0){
				suffix = type.substring((int)id + 1);
				type = type.substring(0, (int)id);
			}
			this.reload();
		}
		public synchronized long next(){
			return ++id;
		}
		
		public void reload(){
			Long l = (Long)db.getObject(type + ".maxId", suffix);
			if(l == null){
				id = 0;
			}else{
				id = l;
			}
		}
	}
	
	private Map<String, Generator> generators = 
		Collections.synchronizedMap(new HashMap<String, Generator>());
	
	private Generator generatorOf(String type){
		Generator g = generators.get(type);
		if(g == null){
			g = new Generator(type);
			generators.put(type, g);
		}
		return g;
	}
	
	//
	public long generate(String type){
		return generatorOf(type).next();
	};
	
	public static void main(String[] args){
	    new IdentifierService().generate("test");
	}
}
